const express = require('express');
const { Op } = require('sequelize');
const { sequelize } = require('../utils/database');
const { User, Activity, Badge, Feed, UserProfile, ActivityParticipant } = require('../models');
const { authenticateToken, isAdmin, isModerator, hasPermission } = require('../middleware/auth');
const { validatePagination } = require('../middleware/validation');
const router = express.Router();

// 为公共统计数据创建单独的路由
const publicStatsRouter = express.Router();

// 系统概览统计（公共访问，不需要认证）
publicStatsRouter.get('/', async (req, res) => {
  try {
    // 获取用户总数
    const userCount = await User.count();
    
    // 获取活动总数
    const activityCount = await Activity.count();
    
    // 获取徽章总数
    const badgeCount = await Badge.count();
    
    // 获取动态总数
    const feedCount = await Feed.count();
    
    // 返回统计数据
    res.json({
      userCount,
      activityCount,
      badgeCount,
      feedCount
    });
  } catch (error) {
    console.error('获取系统概览失败:', error);
    res.status(500).json({
      error: '获取系统概览失败'
    });
  }
});

// 用户增长趋势数据（公共访问）
publicStatsRouter.get('/user-growth', async (req, res) => {
  try {
    // 获取过去7天的日期
    const dates = [];
    const values = [];
    const today = new Date();
    
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];
      dates.push(dateStr);
      
      // 查询该日期注册的用户数
      const startOfDay = new Date(date);
      startOfDay.setHours(0, 0, 0, 0);
      
      const endOfDay = new Date(date);
      endOfDay.setHours(23, 59, 59, 999);
      
      const count = await User.count({
        where: {
          createdAt: {
            [Op.between]: [startOfDay, endOfDay]
          }
        }
      });
      
      values.push(count);
    }
    
    res.json({
      labels: dates,
      values: values
    });
  } catch (error) {
    console.error('获取用户增长趋势失败:', error);
    res.status(500).json({
      error: '获取用户增长趋势失败'
    });
  }
});

// 活动类型分布数据（公共访问）
publicStatsRouter.get('/activity-types', async (req, res) => {
  try {
    // 查询不同类型的活动数量
    const activityTypes = await Activity.findAll({
      attributes: [
        'category_id',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['category_id']
    });
    
    const labels = [];
    const values = [];
    
    activityTypes.forEach(type => {
      // 使用category_id而不是不存在的type字段
      if (type.category_id !== null) {
        // 转换category_id为可读的类型名称
        const categoryNames = {
          1: '学术',
          2: '运动',
          3: '社交',
          4: '文艺',
          5: '志愿'
        };
        labels.push(categoryNames[type.category_id] || `类型${type.category_id}`);
        values.push(parseInt(type.get('count')));
      }
    });
    
    // 如果没有数据，提供一些示例数据
    if (labels.length === 0) {
      res.json({
        labels: ['学术', '运动', '社交', '文艺', '志愿'],
        values: [35, 25, 20, 15, 5]
      });
    } else {
      res.json({
        labels,
        values
      });
    }
  } catch (error) {
    console.error('获取活动类型分布失败:', error);
    res.status(500).json({
      error: '获取活动类型分布失败'
    });
  }
});

// 导出公共统计路由
exports.publicStatsRouter = publicStatsRouter;

// 所有管理员路由都需要认证
router.use(authenticateToken);

// ===== 用户管理 =====

// 获取用户列表（管理员）
router.get('/users', isAdmin, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 50;
    const offset = (page - 1) * limit;
    const { search, status, role, sort_by = 'createdAt', sort_order = 'desc' } = req.query;

    // 构建查询条件
    const whereConditions = {};
    
    // 搜索用户
    if (search) {
      whereConditions[Op.or] = [
        { username: { [Op.like]: `%${search}%` } },
        { email: { [Op.like]: `%${search}%` } }
      ];
    }
    
    // 按状态筛选
    if (status === 'active') {
      whereConditions.is_active = true;
    } else if (status === 'disabled') {
      whereConditions.is_active = false;
    }
    
    // 按角色筛选
    if (role && ['user', 'moderator', 'admin', 'superadmin'].includes(role)) {
      whereConditions.role = role;
    }

    // 构建排序条件
    const validSortFields = ['id', 'username', 'email', 'createdAt', 'last_login'];
    const sortField = validSortFields.includes(sort_by) ? sort_by : 'createdAt';
    const sortDirection = sort_order.toLowerCase() === 'asc' ? 'ASC' : 'DESC';

    const { count, rows: users } = await User.findAndCountAll({
      where: whereConditions,
      attributes: ['id', 'username', 'email', 'role', 'is_active', 'createdAt', 'last_login', 'avatar_url'],
      include: [
        {
          model: UserProfile,
          as: 'profile',
          attributes: ['interests', 'social_level', 'activity_frequency'],
          required: false
        }
      ],
      order: [[sortField, sortDirection]],
      limit,
      offset
    });

    // 获取用户参与的活动和徽章数量
    const userIds = users.map(user => user.id);
    
    // 查询用户的徽章数量
    const badgeCounts = await Badge.findAll({
      attributes: [
        'user_id',
        [sequelize.fn('COUNT', sequelize.col('id')), 'badgeCount']
      ],
      where: { user_id: { [Op.in]: userIds } },
      group: ['user_id']
    });
    
    // 查询用户参与的活动数量
    const activityCounts = await ActivityParticipant.findAll({
      attributes: [
        'user_id',
        [sequelize.fn('COUNT', sequelize.col('id')), 'activityCount']
      ],
      where: { user_id: { [Op.in]: userIds } },
      group: ['user_id']
    });
    
    // 创建计数映射
    const badgeCountMap = {};
    const activityCountMap = {};
    
    badgeCounts.forEach(item => {
      badgeCountMap[item.user_id] = parseInt(item.get('badgeCount'));
    });
    
    activityCounts.forEach(item => {
      activityCountMap[item.user_id] = parseInt(item.get('activityCount'));
    });
    
    // 添加计数到用户数据
    const usersWithCounts = users.map(user => {
      const userData = user.toJSON();
      userData.badge_count = badgeCountMap[user.id] || 0;
      userData.activity_count = activityCountMap[user.id] || 0;
      return userData;
    });

    res.json({
      users: usersWithCounts,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({
      error: '获取用户列表失败'
    });
  }
});

// 获取用户详情（管理员）
router.get('/users/:id', isAdmin, async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id, {
      attributes: { exclude: ['password_hash'] },
      include: [
        {
          model: UserProfile,
          as: 'profile',
          required: false
        }
      ]
    });
    
    if (!user) {
      return res.status(404).json({
        error: '用户不存在'
      });
    }
    
    // 获取用户的徽章数量
    const badgeCount = await Badge.count({
      where: { user_id: user.id }
    });
    
    // 获取用户参与的活动数量
    const activityCount = await ActivityParticipant.count({
      where: { user_id: user.id }
    });
    
    // 获取用户创建的活动数量
    const createdActivityCount = await Activity.count({
      where: { creator_id: user.id }
    });
    
    // 获取用户发布的动态数量
    const feedCount = await Feed.count({
      where: { user_id: user.id }
    });
    
    const userData = user.toJSON();
    userData.stats = {
      badge_count: badgeCount,
      activity_count: activityCount,
      created_activity_count: createdActivityCount,
      feed_count: feedCount
    };
    
    res.json(userData);
  } catch (error) {
    console.error('获取用户详情失败:', error);
    res.status(500).json({
      error: '获取用户详情失败'
    });
  }
});

// 更新用户状态（启用/禁用）
router.put('/users/:id/status', isAdmin, async (req, res) => {
  try {
    const { is_active } = req.body;
    
    if (typeof is_active !== 'boolean') {
      return res.status(400).json({
        error: '状态值必须为布尔类型'
      });
    }
    
    const user = await User.findByPk(req.params.id);
    
    if (!user) {
      return res.status(404).json({
        error: '用户不存在'
      });
    }
    
    // 防止管理员禁用自己
    if (user.id === req.user.id && !is_active) {
      return res.status(400).json({
        error: '不能禁用自己的账户'
      });
    }
    
    // 防止禁用超级管理员（除非当前用户也是超级管理员）
    if (user.role === 'superadmin' && req.user.role !== 'superadmin') {
      return res.status(403).json({
        error: '没有权限禁用超级管理员账户'
      });
    }
    
    await user.update({ 
      is_active,
      updated_by: req.user.id
    });
    
    res.json({
      message: `用户 ${user.username} 已${is_active ? '启用' : '禁用'}`,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
        is_active: user.is_active
      }
    });
  } catch (error) {
    console.error('更新用户状态失败:', error);
    res.status(500).json({
      error: '更新用户状态失败'
    });
  }
});

// 更新用户角色
router.put('/users/:id/role', isAdmin, async (req, res) => {
  try {
    const { role } = req.body;
    
    if (!['user', 'moderator', 'admin', 'superadmin'].includes(role)) {
      return res.status(400).json({
        error: '无效的角色值'
      });
    }
    
    const user = await User.findByPk(req.params.id);
    
    if (!user) {
      return res.status(404).json({
        error: '用户不存在'
      });
    }
    
    // 防止管理员降级自己的权限
    if (user.id === req.user.id && role !== user.role) {
      return res.status(400).json({
        error: '不能修改自己的角色'
      });
    }
    
    // 只有超级管理员可以设置或修改超级管理员
    if ((role === 'superadmin' || user.role === 'superadmin') && req.user.role !== 'superadmin') {
      return res.status(403).json({
        error: '只有超级管理员可以管理超级管理员角色'
      });
    }
    
    await user.update({ 
      role,
      updated_by: req.user.id
    });
    
    res.json({
      message: `用户 ${user.username} 的角色已更新为 ${role}`,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role
      }
    });
  } catch (error) {
    console.error('更新用户角色失败:', error);
    res.status(500).json({
      error: '更新用户角色失败'
    });
  }
});

// 更新用户权限
router.put('/users/:id/permissions', isAdmin, async (req, res) => {
  try {
    const { permissions } = req.body;
    
    if (!permissions || typeof permissions !== 'object') {
      return res.status(400).json({
        error: '权限必须是有效的对象'
      });
    }
    
    const user = await User.findByPk(req.params.id);
    
    if (!user) {
      return res.status(404).json({
        error: '用户不存在'
      });
    }
    
    // 防止修改超级管理员的权限
    if (user.role === 'superadmin' && req.user.role !== 'superadmin') {
      return res.status(403).json({
        error: '只有超级管理员可以修改超级管理员的权限'
      });
    }
    
    await user.update({ 
      permissions,
      updated_by: req.user.id
    });
    
    res.json({
      message: `用户 ${user.username} 的权限已更新`,
      user: {
        id: user.id,
        username: user.username,
        permissions: user.permissions
      }
    });
  } catch (error) {
    console.error('更新用户权限失败:', error);
    res.status(500).json({
      error: '更新用户权限失败'
    });
  }
});

// ===== 内容审核 =====

// 获取待审核的活动
router.get('/activities/pending', isModerator, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 50;
    const offset = (page - 1) * limit;

    const { count, rows: activities } = await Activity.findAndCountAll({
      where: { status: 'pending' },
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'avatar_url']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    res.json({
      activities,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取待审核活动失败:', error);
    res.status(500).json({
      error: '获取待审核活动失败'
    });
  }
});

// 审核活动
router.put('/activities/:id/review', isModerator, async (req, res) => {
  try {
    const { status, review_comment } = req.body;
    
    if (!['approved', 'rejected'].includes(status)) {
      return res.status(400).json({
        error: '无效的状态值'
      });
    }
    
    const activity = await Activity.findByPk(req.params.id);
    
    if (!activity) {
      return res.status(404).json({
        error: '活动不存在'
      });
    }
    
    await activity.update({ 
      status,
      review_comment,
      reviewed_at: new Date(),
      reviewed_by: req.user.id
    });
    
    res.json({
      message: `活动已${status === 'approved' ? '批准' : '拒绝'}`,
      activity: {
        id: activity.id,
        title: activity.title,
        status: activity.status,
        review_comment: activity.review_comment
      }
    });
  } catch (error) {
    console.error('审核活动失败:', error);
    res.status(500).json({
      error: '审核活动失败'
    });
  }
});

// 审核动态内容
router.get('/feeds/reported', isModerator, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 50;
    const offset = (page - 1) * limit;

    const { count, rows: feeds } = await Feed.findAndCountAll({
      where: { 
        is_reported: true,
        // 或者使用举报次数
        // report_count: { [Op.gt]: 0 }
      },
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'avatar_url']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    res.json({
      feeds,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取被举报动态失败:', error);
    res.status(500).json({
      error: '获取被举报动态失败'
    });
  }
});

// 处理举报的动态
router.put('/feeds/:id/moderate', isModerator, async (req, res) => {
  try {
    const { action, comment } = req.body;
    
    if (!['approve', 'hide', 'delete'].includes(action)) {
      return res.status(400).json({
        error: '无效的操作'
      });
    }
    
    const feed = await Feed.findByPk(req.params.id);
    
    if (!feed) {
      return res.status(404).json({
        error: '动态不存在'
      });
    }
    
    let result;
    
    switch (action) {
      case 'approve':
        // 标记为已审核，移除举报标记
        result = await feed.update({
          is_reported: false,
          report_count: 0,
          moderated_at: new Date(),
          moderated_by: req.user.id,
          moderation_comment: comment
        });
        break;
        
      case 'hide':
        // 隐藏动态
        result = await feed.update({
          is_public: false,
          is_reported: false,
          is_hidden: true,
          moderated_at: new Date(),
          moderated_by: req.user.id,
          moderation_comment: comment
        });
        break;
        
      case 'delete':
        // 删除动态
        await feed.destroy();
        result = { id: req.params.id, status: 'deleted' };
        break;
    }
    
    res.json({
      message: `动态已${action === 'approve' ? '批准' : action === 'hide' ? '隐藏' : '删除'}`,
      feed: result
    });
  } catch (error) {
    console.error('处理动态失败:', error);
    res.status(500).json({
      error: '处理动态失败'
    });
  }
});

// ===== 统计和报表 =====

// 系统概览统计
router.get('/stats/overview', isAdmin, async (req, res) => {
  try {
    // 用户统计
    const userCount = await User.count();
    const activeUserCount = await User.count({ where: { is_active: true } });
    const newUsersCount = await User.count({
      where: {
        createdAt: {
          [Op.gte]: new Date(new Date() - 7 * 24 * 60 * 60 * 1000) // 过去7天
        }
      }
    });
    
    // 角色分布
    const roleDistribution = await User.findAll({
      attributes: [
        'role',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['role']
    });
    
    // 活动统计
    const activityCount = await Activity.count();
    const pendingActivityCount = await Activity.count({ where: { status: 'pending' } });
    const upcomingActivityCount = await Activity.count({
      where: {
        start_time: { [Op.gt]: new Date() }
      }
    });
    
    // 徽章统计
    const badgeCount = await Badge.count();
    const badgesByRarity = await Badge.findAll({
      attributes: [
        'rarity',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['rarity']
    });
    
    // 动态统计
    const feedCount = await Feed.count();
    const reportedFeedCount = await Feed.count({ where: { is_reported: true } });
    
    // 用户活跃度（每日活跃用户）
    const dailyActiveUsers = await User.count({
      where: {
        last_login: {
          [Op.gte]: new Date(new Date() - 24 * 60 * 60 * 1000) // 过去24小时
        }
      }
    });
    
    // 最近注册用户
    const recentUsers = await User.findAll({
      attributes: ['id', 'username', 'email', 'role', 'createdAt'],
      order: [['createdAt', 'DESC']],
      limit: 5
    });
    
    // 最近登录用户
    const recentLogins = await User.findAll({
      attributes: ['id', 'username', 'email', 'role', 'last_login'],
      where: {
        last_login: { [Op.ne]: null }
      },
      order: [['last_login', 'DESC']],
      limit: 5
    });
    
    res.json({
      users: {
        total: userCount,
        active: activeUserCount,
        newLastWeek: newUsersCount,
        dailyActive: dailyActiveUsers,
        roleDistribution
      },
      activities: {
        total: activityCount,
        pending: pendingActivityCount,
        upcoming: upcomingActivityCount
      },
      badges: {
        total: badgeCount,
        byRarity: badgesByRarity
      },
      feeds: {
        total: feedCount,
        reported: reportedFeedCount
      },
      recentUsers,
      recentLogins
    });
  } catch (error) {
    console.error('获取统计信息失败:', error);
    res.status(500).json({
      error: '获取统计信息失败'
    });
  }
});

// 高级用户分析报表
router.get('/reports/users', isAdmin, async (req, res) => {
  try {
    const { timeframe = 'month' } = req.query;
    
    let startDate;
    const endDate = new Date();
    
    // 设置时间范围
    switch (timeframe) {
      case 'week':
        startDate = new Date(endDate - 7 * 24 * 60 * 60 * 1000);
        break;
      case 'month':
        startDate = new Date(endDate.getFullYear(), endDate.getMonth() - 1, endDate.getDate());
        break;
      case 'quarter':
        startDate = new Date(endDate.getFullYear(), endDate.getMonth() - 3, endDate.getDate());
        break;
      case 'year':
        startDate = new Date(endDate.getFullYear() - 1, endDate.getMonth(), endDate.getDate());
        break;
      default:
        startDate = new Date(endDate.getFullYear(), endDate.getMonth() - 1, endDate.getDate());
    }
    
    // 用户增长趋势（按日统计）
    const userGrowthQuery = `
      SELECT 
        DATE(createdAt) as date,
        COUNT(*) as new_users
      FROM users
      WHERE createdAt BETWEEN :startDate AND :endDate
      GROUP BY DATE(createdAt)
      ORDER BY date ASC
    `;
    
    const [userGrowth] = await sequelize.query(userGrowthQuery, {
      replacements: { startDate, endDate },
      type: sequelize.QueryTypes.SELECT
    });
    
    // 用户活跃度分析
    const userActivityQuery = `
      SELECT 
        DATE(last_login) as date,
        COUNT(*) as active_users
      FROM users
      WHERE last_login BETWEEN :startDate AND :endDate
      GROUP BY DATE(last_login)
      ORDER BY date ASC
    `;
    
    const [userActivity] = await sequelize.query(userActivityQuery, {
      replacements: { startDate, endDate },
      type: sequelize.QueryTypes.SELECT
    });
    
    // 用户参与度（徽章获取情况）
    const badgeAcquisitionQuery = `
      SELECT 
        DATE(minted_at) as date,
        COUNT(*) as badges_earned
      FROM badges
      WHERE minted_at BETWEEN :startDate AND :endDate
      GROUP BY DATE(minted_at)
      ORDER BY date ASC
    `;
    
    const [badgeAcquisition] = await sequelize.query(badgeAcquisitionQuery, {
      replacements: { startDate, endDate },
      type: sequelize.QueryTypes.SELECT
    });
    
    // 活跃度最高的用户
    const mostActiveUsers = await User.findAll({
      attributes: [
        'id', 
        'username', 
        'email',
        'avatar_url',
        'last_login',
        [sequelize.fn('COUNT', sequelize.col('Badges.id')), 'badge_count'],
      ],
      include: [
        {
          model: Badge,
          as: 'badges',
          attributes: [],
          required: false
        }
      ],
      where: {
        last_login: { [Op.between]: [startDate, endDate] }
      },
      group: ['User.id'],
      order: [[sequelize.fn('COUNT', sequelize.col('badges.id')), 'DESC']],
      limit: 10
    });
    
    res.json({
      timeframe,
      period: {
        start: startDate,
        end: endDate
      },
      userGrowth,
      userActivity,
      badgeAcquisition,
      mostActiveUsers
    });
  } catch (error) {
    console.error('生成用户报表失败:', error);
    res.status(500).json({
      error: '生成用户报表失败'
    });
  }
});

// 活动分析报表
router.get('/reports/activities', isAdmin, async (req, res) => {
  try {
    const { timeframe = 'month' } = req.query;
    
    let startDate;
    const endDate = new Date();
    
    // 设置时间范围
    switch (timeframe) {
      case 'week':
        startDate = new Date(endDate - 7 * 24 * 60 * 60 * 1000);
        break;
      case 'month':
        startDate = new Date(endDate.getFullYear(), endDate.getMonth() - 1, endDate.getDate());
        break;
      case 'quarter':
        startDate = new Date(endDate.getFullYear(), endDate.getMonth() - 3, endDate.getDate());
        break;
      case 'year':
        startDate = new Date(endDate.getFullYear() - 1, endDate.getMonth(), endDate.getDate());
        break;
      default:
        startDate = new Date(endDate.getFullYear(), endDate.getMonth() - 1, endDate.getDate());
    }
    
    // 活动创建趋势
    const activityCreationQuery = `
      SELECT 
        DATE(createdAt) as date,
        COUNT(*) as new_activities
      FROM activities
      WHERE createdAt BETWEEN :startDate AND :endDate
      GROUP BY DATE(createdAt)
      ORDER BY date ASC
    `;
    
    const [activityCreation] = await sequelize.query(activityCreationQuery, {
      replacements: { startDate, endDate },
      type: sequelize.QueryTypes.SELECT
    });
    
    // 活动参与趋势
    const activityParticipationQuery = `
      SELECT 
        DATE(createdAt) as date,
        COUNT(*) as new_participations
      FROM activity_participants
      WHERE createdAt BETWEEN :startDate AND :endDate
      GROUP BY DATE(createdAt)
      ORDER BY date ASC
    `;
    
    const [activityParticipation] = await sequelize.query(activityParticipationQuery, {
      replacements: { startDate, endDate },
      type: sequelize.QueryTypes.SELECT
    });
    
    // 活动分类统计
    const activityCategoryStats = await Activity.findAll({
      attributes: [
        'category_id',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: {
        createdAt: { [Op.between]: [startDate, endDate] }
      },
      group: ['category_id']
    });
    
    // 最受欢迎的活动
    const popularActivities = await Activity.findAll({
      attributes: [
        'id', 
        'title', 
        'location',
        'start_time',
        'status',
        [sequelize.fn('COUNT', sequelize.col('participants.id')), 'participant_count'],
      ],
      include: [
        {
          model: ActivityParticipant,
          as: 'participants',
          attributes: [],
          required: false
        },
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'avatar_url']
        }
      ],
      where: {
        createdAt: { [Op.between]: [startDate, endDate] }
      },
      group: ['Activity.id', 'creator.id'],
      order: [[sequelize.fn('COUNT', sequelize.col('participants.id')), 'DESC']],
      limit: 10
    });
    
    res.json({
      timeframe,
      period: {
        start: startDate,
        end: endDate
      },
      activityCreation,
      activityParticipation,
      activityCategoryStats,
      popularActivities
    });
  } catch (error) {
    console.error('生成活动报表失败:', error);
    res.status(500).json({
      error: '生成活动报表失败'
    });
  }
});

// 徽章系统分析报表
router.get('/reports/badges', isAdmin, async (req, res) => {
  try {
    const { timeframe = 'month' } = req.query;
    
    let startDate;
    const endDate = new Date();
    
    // 设置时间范围
    switch (timeframe) {
      case 'week':
        startDate = new Date(endDate - 7 * 24 * 60 * 60 * 1000);
        break;
      case 'month':
        startDate = new Date(endDate.getFullYear(), endDate.getMonth() - 1, endDate.getDate());
        break;
      case 'quarter':
        startDate = new Date(endDate.getFullYear(), endDate.getMonth() - 3, endDate.getDate());
        break;
      case 'year':
        startDate = new Date(endDate.getFullYear() - 1, endDate.getMonth(), endDate.getDate());
        break;
      default:
        startDate = new Date(endDate.getFullYear(), endDate.getMonth() - 1, endDate.getDate());
    }
    
    // 徽章发放趋势
    const badgeMintingQuery = `
      SELECT 
        DATE(minted_at) as date,
        COUNT(*) as badges_minted,
        rarity
      FROM badges
      WHERE minted_at BETWEEN :startDate AND :endDate
      GROUP BY DATE(minted_at), rarity
      ORDER BY date ASC
    `;
    
    const [badgeMinting] = await sequelize.query(badgeMintingQuery, {
      replacements: { startDate, endDate },
      type: sequelize.QueryTypes.SELECT
    });
    
    // 徽章稀有度分布
    const badgeRarityDistribution = await Badge.findAll({
      attributes: [
        'rarity',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: {
        minted_at: { [Op.between]: [startDate, endDate] }
      },
      group: ['rarity']
    });
    
    // 徽章获取榜单
    const badgeLeaderboard = await User.findAll({
      attributes: [
        'id', 
        'username', 
        'avatar_url',
        [sequelize.fn('COUNT', sequelize.col('badges.id')), 'badge_count'],
      ],
      include: [
        {
          model: Badge,
          as: 'badges',
          attributes: [],
          where: {
            minted_at: { [Op.between]: [startDate, endDate] }
          },
          required: true
        }
      ],
      group: ['User.id'],
      order: [[sequelize.fn('COUNT', sequelize.col('badges.id')), 'DESC']],
      limit: 10
    });
    
    // 最受欢迎的徽章
    const popularBadges = await Badge.findAll({
      attributes: [
        'badge_name',
        'badge_description',
        'rarity',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: {
        minted_at: { [Op.between]: [startDate, endDate] }
      },
      group: ['badge_name', 'badge_description', 'rarity'],
      order: [[sequelize.fn('COUNT', sequelize.col('id')), 'DESC']],
      limit: 10
    });
    
    res.json({
      timeframe,
      period: {
        start: startDate,
        end: endDate
      },
      badgeMinting,
      badgeRarityDistribution,
      badgeLeaderboard,
      popularBadges
    });
  } catch (error) {
    console.error('生成徽章报表失败:', error);
    res.status(500).json({
      error: '生成徽章报表失败'
    });
  }
});

// 修改模块导出
module.exports = router;
module.exports.publicStatsRouter = publicStatsRouter; 